package com.longrise.android.byjk.plugins.aboutme.personalInfo.product_show;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.longrise.LEAP.Base.Objects.EntityBean;
import com.longrise.android.byjk.R;
import com.longrise.common.base.BaseActivity;
import com.longrise.android.byjk.model.UserInfor;
import com.longrise.android.byjk.plugins.aboutme.personalInfo.request.BaseRequestResult;
import com.longrise.android.byjk.plugins.aboutme.personalInfo.request.PersionRequest;
import com.longrise.common.utils.DZZWTools;
import com.longrise.common.utils.NetUtil;

/**
 * Created by callxkj on 2016/11/21.
 * 添加产品展示
 */

public class AddProductShowActivity extends BaseActivity implements View.OnClickListener {

    private static final String TAG = "AddProductShowActivity";

    private final String SAVEINSANCE_IS_CURRENT = "SAVE_IS_CURRENT";
    private final String SAVEINSTANCE_PRODUCT_ID = "SAVE_PRODUCT_ID";
    private final String SAVEINSTANCE_IS_INTEGRAL = "SAVEINSTANCE_IS_INTEGRAL";

    private Toolbar mTitle;
    private RelativeLayout mRight;

    private EditText mEditName;
    private EditText mEditDesc;

    private View mLoading;

    private String mID = "";
    private boolean mIsCurrent;   //确认保存或者修改是否成功
    private boolean mIntegralFrom;  //确认当前是否是积分过来

    @Override
    public int getContentViewId(@Nullable Bundle state) {
        if (state != null) {
            onRestoreState(state);
        } else {
            getExtraData();
        }
        return R.layout.activity_addproductshow;
    }

    @Override
    public void initView() {
        mEditDesc = (EditText) findViewById(R.id.addproductshow_character);
        mEditName = (EditText) findViewById(R.id.addproductshow_phonenum);
        mLoading = findViewById(R.id.rela_load_xqpc);
        showLoading(false);
        initData();
        initTitle();
    }

    private void initTitle() {
        mTitle = (Toolbar) findViewById(R.id.byjk_toolbar);
        mTitle.setTitle(getString(R.string.cpzs));
        setSupportActionBar(mTitle);
        mTitle.setNavigationOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                close();
            }
        });
        mRight = (RelativeLayout) mTitle.findViewById(R.id.bb_toolbar_right_rl_tv);
        mRight.setVisibility(View.VISIBLE);
        mRight.setOnClickListener(this);
        TextView rightText = (TextView) mTitle.findViewById(R.id.iv_toolbar_right_tv);
        rightText.setText(getString(R.string.savepic));
    }

    private void initData() {
        Intent extra = getIntent();
        mEditName.setText(extra.getStringExtra("productname"));
        mEditName.requestFocus();
        mEditDesc.setText(extra.getStringExtra("productdesc"));
        String name = mEditName.getText().toString().trim();
        if (!TextUtils.isEmpty(name)) {
            mEditName.setSelection(name.length());
        }
    }

    private void getExtraData() {
        Intent intent = getIntent();
        mID = intent.getStringExtra("productid");

//        String value = intent.getStringExtra(BBWebHelper.FROM_PAGE);
//        if (value != null && value.equals(BBWebHelper.PAGE_NAME)) {
//            mIntegralFrom = true;
//        } else {
//            mIntegralFrom = false;
//        }
    }

    private void onRestoreState(Bundle state) {
        if (state != null) {
            mID = state.getString(SAVEINSTANCE_PRODUCT_ID);
            mIsCurrent = state.getBoolean(SAVEINSANCE_IS_CURRENT);
            mIntegralFrom = state.getBoolean(SAVEINSTANCE_IS_INTEGRAL);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    private void commitRequest(EntityBean re, String url) {
        mRight.setClickable(false);
        showLoading(true);
        PersionRequest persionRequest = new PersionRequest(new AddProductResult());
        persionRequest.request(this, url, re);
    }

    private class AddProductResult extends BaseRequestResult {

        @Override
        public void onSuccess(EntityBean bean) {
            try {
                if (bean != null) {
                    int resultstate = bean.getInt("resultstate");
                    if (resultstate == 1) {
                        //需要返回一个相关数据用于设置个人资料页
                        showToast(getString(R.string.save_produect_success));
                        mIsCurrent = true;
                        EntityBean result = bean.getBean("result");
                        UserInfor.getInstance().setUserCPZS(result.getString("showname"));
                        parseIntegral(result);
                        updateSaveBtnState(false);
                    } else {
                        showToast(bean.getString("resultdesc"));
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onFailure(String error) {
            //错误处理
            showToast(getString(R.string.nonetwork));
        }

        @Override
        public void onFinish() {
            mRight.setClickable(true);
            showLoading(false);
        }

    }

    private void parseIntegral(EntityBean integral) {
//        if (!mIntegralFrom) {
//            close();
//            return;
//        }
        String infostate = integral.getString("infostate");  //状态
        String acquiredscore = integral.getString("acquiredscore"); //获取的积分
        String remindwords = integral.getString("remindwords");  //提示语
        if (infostate != null && infostate.equals("1")) { //任务完成
//            MyIntegralDialogUtil.showIntegralDailog(this, acquiredscore, remindwords, mIntegralFrom);
        } else if (infostate != null && infostate.equals("0")) {
            //否则提示server msg 完成失败 或者 已完成过
            showToast(remindwords);
        } else {
            //已经完成过了
        }
        close();
    }

    /**
     * 当前产品方案保存之后，隐藏保存
     * 最多添加三个产品方案，否则不能添加成功
     */
    private void updateSaveBtnState(boolean isClick) {
        mRight.setVisibility(isClick ? View.VISIBLE : View.GONE);
    }

    private boolean checkNetwork() {
        if (!NetUtil.checkNetEnable()) {
            return false;
        } else {
            return true;
        }
    }

    private void save() {
        String desc = mEditDesc.getText().toString().trim();
        String name = mEditName.getText().toString().trim();
        if (TextUtils.isEmpty(name)) {
            DZZWTools.showToast(this, getString(R.string.productname_isnull), Toast.LENGTH_SHORT);
            return;
        }
        if (TextUtils.isEmpty(desc)) {
            DZZWTools.showToast(this, getString(R.string.productdesc_isnull), Toast.LENGTH_SHORT);
            return;
        }
        EntityBean bean = new EntityBean();
        bean.set("userid", UserInfor.getInstance().getUserid());
        bean.set("cardno", UserInfor.getInstance().getUsersfzh());
        bean.set("productid", mID);
        bean.set("productname", name);
        bean.set("productdesc", desc);
        EntityBean reqBean = new EntityBean();
        reqBean.set("bean", bean);
        if (TextUtils.isEmpty(mID)) {
            commitRequest(reqBean, "bbt_user_iInsuranceProduct");
        } else {
            commitRequest(reqBean, "bbt_user_uInsuranceProduct");
        }
    }

    private void close() {
        setResult(RESULT_OK, new Intent().putExtra("key", mIsCurrent));
        finish();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.bb_toolbar_right_rl_tv:
                if (checkNetwork()) {
                    save();
                }
                break;
        }
    }

    private void showLoading(boolean isLoading) {
        mLoading.setVisibility(isLoading ? View.VISIBLE : View.GONE);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putString(SAVEINSTANCE_PRODUCT_ID, mID);
        outState.putBoolean(SAVEINSANCE_IS_CURRENT, mIsCurrent);
        outState.putBoolean(SAVEINSTANCE_IS_INTEGRAL, mIntegralFrom);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            close();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
}
